/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.babble.subitem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.babble.blog.feign.IBlogClient;
import com.babble.blog.vo.BlogVO;
import com.babble.subitem.conversion.CollectionConversion;
import com.babble.subitem.dto.QueryCollectDTO;
import com.babble.subitem.entity.Collect;
import com.babble.subitem.entity.Subject;
import com.babble.subitem.mapper.CollectMapper;
import com.babble.subitem.service.ICollectService;
import com.babble.subitem.vo.CollectVO;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.json.JSONObject;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.enums.CodeMsg;
import org.springblade.common.exception.MsgException;
import org.springblade.common.tool.PageUtil;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.RedisUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏表 服务实现类
 *
 * @author Blade
 * @since 2021-11-21
 */
@Service
@RequiredArgsConstructor
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {
	public final CollectionConversion collectionConversion;
	public final IBlogClient blogClient;
	public final RedisUtil redisUtil;

	@Override
	public IPage<CollectVO> selectCollectPage(IPage<CollectVO> page, CollectVO collect) {
		return page.setRecords(baseMapper.selectCollectPage(page, collect));
	}
	@Override
	public void saveToCol(String id) throws MsgException {
		//是否已经收藏
		colsIsExet(id);
		//TODO (cyq)判断文章是否存在,抛异常
		R<List<BlogVO>> blogs = blogClient.listOfBlogCategory(id);
		Collect collect = new Collect();
		collect.setUserId(SecureUtil.getUser().getUserId().toString());
		collect.setBlogId(id);
		collect.setCreateTime(LocalDateTime.now());
		collect.setUpdateTime(LocalDateTime.now());
		this.save(collect);
		//往redis添加
		CollectVO collectVO = collectionConversion.CollectToCollectVO(collect);
		//TODO （cyq）添加收藏博客的name
//		collectVO.setBlogName(blogs.getData().get(0).getTitle());
		addCollect(collectVO);
 		}

	private void colsIsExet(String id) throws MsgException {
		List<CollectVO> list = listColVO(new QueryCollectDTO());
		List<CollectVO> cols = list.stream().filter(item -> {
			if (item.getUserId().equals(SecureUtil.getUser().getUserId()) && item.getBlogId().equals(id)) {
				return true;
			}
			return false;
		}).collect(Collectors.toList());
		if(cols!=null && cols.size()!=0){
			throw new MsgException(CodeMsg.BLOG_COLLECT_YES_ERROR.getCode(),CodeMsg.BLOG_COLLECT_YES_ERROR.getMsg());
		}
	}

	@Override
	public void delToCol(String id) throws MsgException {
		//判断是否本人
		Long userId = SecureUtil.getUser().getUserId();
		List<CollectVO> cols = listColVOById(new QueryCollectDTO());
		List<CollectVO> collectVOS = cols.stream().filter(item->{
			if(item.getId().equals(id) && item.getUserId().equals(userId.toString())){
				return true;
			}
			return false;
		}).collect(Collectors.toList());
		if(collectVOS!=null && collectVOS.size()>0){
			this.removeById(id);
			//修改redis
			delCollect(id);
			return;
		}
		throw new MsgException(CodeMsg.BLOG_COLLECT_NOT_USER_ERROR.getCode(),CodeMsg.BLOG_COLLECT_NOT_USER_ERROR.getMsg());
	}

	@Override
	public List<CollectVO> listColVO(QueryCollectDTO queryCollectDTO) {
		Object json = redisUtil.get(CacheNames.BLOG_COLLECTS);
		if(json == null){
			Page<Collect> page = this.page(new Page<Collect>(),new QueryWrapper<Collect>().orderByAsc("create_time"));
			List<CollectVO> collect = page.getRecords().stream().map(item -> {
				CollectVO colVO = collectionConversion.CollectToCollectVO(item);
				//TODO(cyq)通过ID ES查找到博客名称
				R<List<BlogVO>> listR = blogClient.listOfBlogCategory(item.getId());
//				colVO.setBlogName(listR.getData().get(0).getTitle());
				return colVO;
			}).collect(Collectors.toList());
			redisUtil.set(CacheNames.BLOG_COLLECTS, JSON.toJSON(collect));
			if(queryCollectDTO.getSize()==null && queryCollectDTO.getCurrent()==null){
				return collect;
			}
			return PageUtil.startPage(collect,queryCollectDTO.getCurrent(),queryCollectDTO.getSize());
		}
		List<CollectVO> cols = JSONArray.parseArray(json.toString(), CollectVO.class);
		if(queryCollectDTO.getSize()==null && queryCollectDTO.getCurrent()==null){
			return cols;
		}
		return PageUtil.startPage(cols,queryCollectDTO.getCurrent(),queryCollectDTO.getSize());
	}

	@Override
	public List<CollectVO> listColVOById(QueryCollectDTO queryCollectDTO) {
		Long userId = SecureUtil.getUser().getUserId();
		List<CollectVO> collectVOS = listColVO(new QueryCollectDTO());
		List<CollectVO> collect = collectVOS.stream().filter(item -> {
			if (item.getUserId().equals(userId.toString())) {
				return true;
			}
			return false;
		}).collect(Collectors.toList());
		if(queryCollectDTO.getSize()==null&&queryCollectDTO.getCurrent()==null){
			return collect;
		}
		return PageUtil.startPage(collect,queryCollectDTO.getCurrent(),queryCollectDTO.getSize());

	}

	//传入的对象增加redis
	private void addCollect(CollectVO colVO) {
		List<CollectVO> list = listColVO(new QueryCollectDTO());
		list.add(colVO);
		redisUtil.set(CacheNames.BLOG_COLLECTS, JSON.toJSON(list));
	}
	//传入的对象删除redis
	private void delCollect(String id) {
		List<CollectVO> list = listColVO(new QueryCollectDTO());

		redisUtil.set(CacheNames.BLOG_COLLECTS, JSON.toJSON(list.stream().filter(item->{
			if(item.getId().equals(id)){
				return false;
			}
			return true;
		}).collect(Collectors.toList())));
	}
}
